﻿using Microsoft.AspNetCore.Http;
using System;
using VisionCloud.Api.Auth;
using VisionCloud.Api.Controllers;

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// Cookies的帮助类
    /// </summary>
    public static class CookiesHelper
    {
        public const string CookiesName = "MSCloudWebData";

        /// <summary>
        /// 设置cookiet方法
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="cookiesKey">key</param>
        /// <param name="cookiesValue">value</param>
        public static void SetCookiet(this ApiBaseController controller, string cookiesKey, string cookiesValue)
        {
            controller.HttpContext.Response.Cookies.Append(cookiesKey, cookiesValue, new CookieOptions
            {
                HttpOnly = true,
                Expires = new DateTimeOffset(AuthCore.GetCookiesExpires()),
                Secure = true
            });
        }

        /// <summary>
        /// 删除cookies
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="cookiesKey">key</param>
        public static void DeleteCookies(this ApiBaseController controller, string cookiesKey)
        {
            controller.HttpContext.Response.Cookies.Delete(cookiesKey);
        }

        /// <summary>
        ///  获取指定cookiesKey的值
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="cookiesKey">key</param>
        /// <returns>返回值</returns>
        public static string GetCookies(this ApiBaseController controller, string cookiesKey)
        {
            controller.HttpContext.Request.Cookies.TryGetValue(cookiesKey, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }

        /// <summary>
        ///  获取指定cookiesKey的值
        /// </summary>
        /// <param name="httpContext">httpContext</param>
        /// <param name="cookiesKey">key</param>
        /// <returns>返回值</returns>
        public static string GetCookies(this HttpContext httpContext, string cookiesKey)
        {
            httpContext.Request.Cookies.TryGetValue(cookiesKey, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
    }
}